package com.ks.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ks.core.base.OperationContext;
import com.ks.core.constant.Const;
import com.ks.core.constant.DatePanel;
import com.ks.core.dto.SearchCriteriaBase;
import com.ks.core.exception.GunsException;
import com.ks.core.util.MD5Util;
import com.ks.core.util.ToolUtil;
import com.ks.user.dao.OrgTenantMapper;
import com.ks.user.entity.OrgBase;
import com.ks.user.entity.OrgTenant;
import com.ks.user.service.IOrgBaseService;
import com.ks.user.service.IOrgTenantService;
import com.ks.user.service.IUserBaseService;
import com.ks.user.service._ServiceBase;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

//import com.ks.core.dto.SearchCriteriaBase;

/**
 * <p>
 * 租户 服务实现类
 * </p>
 *
 * @author kingdee123
 * @since 2020-11-30
 */
@Service
public class OrgTenantServiceImpl extends _ServiceBase<OrgTenantMapper, OrgTenant> implements IOrgTenantService {

    @Resource
    private OrgTenantMapper orgTenantMapper;
    @Resource
    private IOrgBaseService orgBaseService;
    @Resource
    private IUserBaseService userBaseService;

    @Override
    public Map<String, Object> getTenantAdminCount(OperationContext context) {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper<OrgTenant> wrapper = new EntityWrapper<>();
        OrgTenant orgTenant = new OrgTenant();
        orgTenant.setDelMark(Const.DEL_FLAG_NORMAL);
        orgTenant.setSexamineStatus(Const.DEL_FLAG_DEL);
        wrapper.setEntity(orgTenant);
        Integer integer = orgTenantMapper.selectCount(wrapper);
        map.put("CardName", "入驻企业数");
        map.put("DataCount", "1");
        List list = new ArrayList();
        DatePanel panel = new DatePanel();
        panel.setDataTime(new Date());
        panel.setDataValue(integer);
        panel.setValueType("STR");
        list.add(panel);
        map.put("date", list);
        return map;
    }

    @Override
    public Map<String, Object> getTenantList() {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper<OrgTenant> wrapper = new EntityWrapper<>();
        OrgTenant orgTenant = new OrgTenant();
        orgTenant.setDelMark(Const.DEL_FLAG_NORMAL);
        orgTenant.setSexamineStatus(Const.SysUser.IS_OK);
        wrapper.setEntity(orgTenant);
        List<OrgTenant> orgTenants = orgTenantMapper.selectList(wrapper);
        map.put("list", orgTenants);
        return map;
    }

    @Override
    public int addOrgTenant(OrgTenant orgTenant) {
        EntityWrapper<OrgTenant> wrapper = new EntityWrapper<>();
        OrgTenant tenant = new OrgTenant();
        tenant.setIcontactsMobile(orgTenant.getIcontactsMobile());
        wrapper.setEntity(tenant);
        wrapper.and("sexamineStatus!=2");
        Integer integer = orgTenantMapper.selectCount(wrapper);
        if (integer > 0) {
            throw new GunsException("已经提交过入驻了,请不要重复提交！！！");
        }

        Integer insert = orgTenantMapper.insert(orgTenant);
        if (insert > 0) {
            return insert;
        }
        return 0;
    }

    @Override
    public int updateOrgTenant(OrgTenant orgTenant) {
        Integer integer = orgTenantMapper.updateById(orgTenant);
        return integer;
    }

    @Override
    public int examineTenant(OperationContext operationContext, int tenantId, int code, String tenantCode, String remark) {
        OrgTenant orgTenant = orgTenantMapper.selectById(tenantId);
        if (ToolUtil.isNotEmpty(orgTenant)) {
            if (!orgTenant.getSexamineStatus().equals(Const.DEL_FLAG_NORMAL)) {
                throw new GunsException("该租户已经被审核过，不能在继续审核！！！");
            } else {
                if (code == Const.SysUser.IS_OK) {

                    OrgTenant tenant = queryTenantCode(tenantCode);
                    if (ToolUtil.isNotEmpty(tenant)) {
                        throw new GunsException("租户编码已经存在，请重新填写新的编码！！！");
                    }
                    //通过审核
                    orgTenant.setIManagerSystem(MD5Util.getMD5(orgTenant.getId() + tenantCode));
                    orgTenant.setSexamineStatus(code);
                    orgTenant.setITenantCode(tenantCode);
                    int i = orgBaseService.insetOrgBase(operationContext, orgTenant.getITenantCode(), orgTenant.getIName(), orgTenant.getId());
                    orgTenant.setOrgID(i);
                    Integer integer = orgTenantMapper.updateById(orgTenant);
                    //TODO  差发送短信给租户后台地址
                    return integer;
                } else if (code == Const.SysUser.IS_NOT_OK) {
                    orgTenant.setSexamineStatus(code);
                    orgTenant.setIRemake(remark);
                    Integer integer = orgTenantMapper.updateById(orgTenant);
                    return integer;
                } else {
                    throw new GunsException("状态值不正确,请核对！！！");
                }
            }

        } else {
            throw new GunsException("租户Id错误。未查询到该租户");
        }

    }

    public OrgTenant queryTenantCode(String tenantCode) {
        OrgTenant orgTenant = new OrgTenant();
        orgTenant.setITenantCode(tenantCode);
        OrgTenant tenant = orgTenantMapper.selectOne(orgTenant);
        return tenant;
    }

    @Override
    public Map<String, Object> getTenantList(OperationContext operationContext, SearchCriteriaBase searchCriteriaBase) {
        Map<String, Object> map = new HashMap<>();
        EntityWrapper<OrgTenant> wrapper = new EntityWrapper<>();
        OrgTenant orgTenant = new OrgTenant();
        orgTenant.setDelMark(Const.DEL_FLAG_NORMAL);
        ArrayList<SearchCriteriaBase.matchField> fields = searchCriteriaBase.getFields();
        if (ToolUtil.isNotEmpty(fields)) {
            for (SearchCriteriaBase.matchField field : fields) {
                if ("iName".equals(field.getName())) {
                    orgTenant.setIName(field.getValue());
                }
                if ("icontactsName".equals(field.getName())) {
                    orgTenant.setIcontactsName(field.getValue());
                }
                if ("icontactsMobile".equals(field.getName())) {
                    orgTenant.setIcontactsMobile(field.getValue());
                }
                if ("iTenantCode".equals(field.getName())) {
                    orgTenant.setITenantCode(field.getValue());
                }
            }
        }
        ArrayList<SearchCriteriaBase.StateField> states = searchCriteriaBase.getStates();
        if (ToolUtil.isNotEmpty(states)) {
            for (SearchCriteriaBase.StateField state : states) {
                if ("sexamineStatus".equals(state.getName())) {
                    orgTenant.setSexamineStatus(Integer.valueOf(state.getValue()));
                }
            }
        }
        wrapper.setEntity(orgTenant);
        if (ToolUtil.isNotEmpty(searchCriteriaBase.getStartTime())) {
            wrapper.and("DATE_FORMAT( createTime, '%Y-%m-%d' ) >=" + "'" + searchCriteriaBase.getStartTime() + "'");
            wrapper.and("DATE_FORMAT( createTime, '%Y-%m-%d' ) <=  " + "'" + searchCriteriaBase.getEndTime() + "'");
        }
        wrapper.orderBy("createTime desc");
        Integer integer = orgTenantMapper.selectCount(wrapper);
        map.put("count", integer);
        List<OrgTenant> orgTenants = orgTenantMapper.selectPage(new Page(searchCriteriaBase.getPageIndex(), searchCriteriaBase.getLimit()), wrapper);
        map.put("orgTenants", orgTenants);
        return map;
    }

    @Override
    public OrgTenant getSystemRootUrl(String RootUrl) {
        OrgTenant orgTenant = new OrgTenant();
        orgTenant.setIManagerSystem(RootUrl);
        orgTenant.setSexamineStatus(Const.SysUser.IS_OK);
        OrgTenant tenant = orgTenantMapper.selectOne(orgTenant);
        if (ToolUtil.isNotEmpty(tenant)) {
            return tenant;
        }
        throw new GunsException("租户后台地址错误！！！");
    }

    @Override
    public OrgTenant getOrgTenantInfo(OperationContext operationContext) {

        OrgTenant orgTenant = orgTenantMapper.selectById(operationContext.getTenantId());
        if (ToolUtil.isNotEmpty(orgTenant)) {
            EntityWrapper<OrgBase> wrapper = new EntityWrapper<>();
            OrgBase orgBase = new OrgBase();
            orgBase.setTenantID(orgTenant.getTenantID());
            orgBase.setDelMark(Const.DEL_FLAG_NORMAL);
            wrapper.setEntity(orgBase);
            List<OrgBase> orgBases = orgBaseService.selectList(wrapper);
            if (ToolUtil.isNotEmpty(orgBases)) {
                orgTenant.setImgLogo(orgBases.get(0).getITenantimg());
            }
            return orgTenant;
        }

        return null;
    }

    @Override
    public int delOrgTenantInfo(OperationContext operationContext, OrgTenant orgTenant) {
        OrgTenant tenant = orgTenantMapper.selectById(orgTenant.getId());
        if (ToolUtil.isNotEmpty(tenant)) {
            tenant.setDelMark(Const.DEL_FLAG_DEL);
            Integer integer = orgTenantMapper.updateById(tenant);
            return integer;
        }
        return 0;
    }


}
